package org.example.chatroom.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.example.chatroom.common.component.OnlineUserManager;
import org.example.chatroom.common.pojo.dataobject.Message;
import org.example.chatroom.common.pojo.dataobject.UserInfo;
import org.example.chatroom.common.pojo.request.WebSocketMessageRequest;
import org.example.chatroom.common.pojo.response.TokenUser;
import org.example.chatroom.common.pojo.response.WebSocketMessageResponse;
import org.example.chatroom.common.util.JWTUtils;
import org.example.chatroom.service.DialogueService;
import org.example.chatroom.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-06-29
 * Time: 20:48
 */
@Component
public class WebSocketApi extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Autowired
    private ObjectMapper objectMapper;
    @Resource(name = "dialogueServiceImpl")
    private DialogueService dialogueService;
    @Resource(name = "messageServiceImpl")
    private MessageService messageService;

    private TokenUser getuser(WebSocketSession session){
        //从session中获得user
        String token = (String) session.getAttributes().get("token");
        //判断token是否存在
        if(token==null){
            System.out.println("用户不存在");
            return null;
        }
        TokenUser tokenUser = (TokenUser) JWTUtils.parseToken(token);
        return tokenUser;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //webSocket连接建立成功之后，会被自动调用
        System.out.println("连接建立成功");
        TokenUser tokenUser = getuser(session);
                //把这个键值对给存起来
        onlineUserManager.online(tokenUser.getId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //webSocket收到消息后会被调用
        System.out.println("收到消息");
        //1. 首先获得当前用户信息，后续要进行消息转发
        TokenUser tokenUser = getuser(session);
        //2. 针对请求进行解析，把json类型的字符串，转成一个java中的对象
        WebSocketMessageRequest req = objectMapper.readValue(message.getPayload(),WebSocketMessageRequest.class);
        if(req.getType().equals("message")){
            //就进行消息转发

        }
    }

    //消息转发（传入发送信息的对象，和发送的信息）
    private void transferMessage(TokenUser fromUser,WebSocketMessageRequest req) throws IOException {
        //1. 首先先构建一个带转发的响应对象
        WebSocketMessageResponse resp = new WebSocketMessageResponse("message",
                fromUser.getId(), fromUser.getUserName(), req.getDialogueId(),req.getContent());
        //把对象转为json格式字符串
        String respjson = objectMapper.writeValueAsString(resp);
        System.out.println("[transferMessage] respJson: " + respjson);
        //2. 通过请求中的dialogueId 获取整个会话中有那些userId
        List<Integer> userIds = dialogueService.getUserId(resp.getDialogueId());
        //3. 循环列表，给列表的每个好友发送信息
        for (Integer userId : userIds){
            //查找用户是否在线，在线发送实时信息
            WebSocketSession webSocketSession = onlineUserManager.getsession(userId);
            if(webSocketSession==null){
                //用户不在线，不发送实时信息
                continue;
            }
            webSocketSession.sendMessage(new TextMessage(respjson));
        }
        //转发的信息，还需要放在数据库中，后续用户下线，重新上线访问数据库拿到历史记录
        Message message = new Message();
        message.setUserId(fromUser.getId());
        message.setDialogueId(req.getDialogueId());
        message.setContent(req.getContent());
        messageService.add(message);
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //连接失败时会被调用
        System.out.println("连接失败");
        TokenUser tokenUser = getuser(session);
        if(tokenUser==null){
            return;
        }
        onlineUserManager.offline(tokenUser.getId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //连接正常关闭后会被自动调用
        System.out.println("连接正常关闭");
        TokenUser tokenUser = getuser(session);
        if(tokenUser==null){
            return;
        }
        onlineUserManager.offline(tokenUser.getId(), session);
    }
}